package com.webserver.core;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 该类维护请求路径与Controller处理方法的对应关系
 * @author Chen
 */
public class HandlerMapping {
    private static Map<String, Method> mapping = new HashMap<>();

    static {
        initMapping();
    }

    private static void initMapping() {
        try {
            File root = new File(
                    BirdBootApplication.primarySource.getResource(".").toURI()
            );
            File dir = new File(root, "controller");
            if (!dir.exists()) {
                return;
            }
            File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
            for (File sub : subs) {
                String fileName = sub.getName();
                String className = fileName.substring(0, fileName.indexOf("."));
                String packageName = BirdBootApplication.primarySource.getPackage().getName();
                className = packageName + ".controller." + className;
                Class<?> cls = Class.forName(className);
                if (cls.isAnnotationPresent(Controller.class)) {
                    Method[] methods = cls.getDeclaredMethods();
                    for (Method method : methods) {
                        if (method.isAnnotationPresent(RequestMapping.class)) {
                            RequestMapping rm = method.getAnnotation(RequestMapping.class);
                            String value = rm.value();
                            mapping.put(value, method);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Method getMethod(String path) {
        return mapping.get(path);
    }
}
